package com.example.socialapp.ui.bookmark

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.BookmarkRemove
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.outlined.InsertComment
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue
import kotlin.random.Random

/**
 * 书签/收藏界面
 *
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToUserProfile 导航到用户资料界面回调
 * @param onNavigateToPostDetail 导航到动态详情界面回调
 * @param onNavigateToSearch 导航到搜索界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BookmarkScreen(
    onNavigateBack: () -> Unit,
    onNavigateToUserProfile: (String) -> Unit = {},
    onNavigateToPostDetail: (String) -> Unit = {},
    onNavigateToSearch: () -> Unit = {}
) {
    // 在实际应用中应从ViewModel获取收藏数据
    val bookmarks = remember { generateSampleBookmarks(15) }
    var showMenu by remember { mutableStateOf(false) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("我的收藏") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = onNavigateToSearch) {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索收藏"
                        )
                    }
                    IconButton(onClick = { showMenu = true }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                        
                        DropdownMenu(
                            expanded = showMenu,
                            onDismissRequest = { showMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text("编辑收藏") },
                                onClick = { 
                                    showMenu = false 
                                    /* 进入编辑模式 */ 
                                }
                            )
                            DropdownMenuItem(
                                text = { Text("整理收藏") },
                                onClick = { 
                                    showMenu = false 
                                    /* 进入整理模式 */ 
                                }
                            )
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { innerPadding ->
        if (bookmarks.isEmpty()) {
            // 空状态
            EmptyBookmarks(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding)
            )
        } else {
            // 书签列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding)
            ) {
                items(bookmarks) { bookmark ->
                    BookmarkItem(
                        bookmark = bookmark,
                        onPostClick = { onNavigateToPostDetail(bookmark.id) },
                        onAuthorClick = { onNavigateToUserProfile(bookmark.authorId) },
                        onRemoveBookmark = { /* 移除收藏逻辑 */ }
                    )
                    Divider()
                }
            }
        }
    }
}

/**
 * 书签项组件
 */
@Composable
private fun BookmarkItem(
    bookmark: Bookmark,
    onPostClick: () -> Unit,
    onAuthorClick: () -> Unit,
    onRemoveBookmark: () -> Unit
) {
    var isLiked by remember { mutableStateOf(bookmark.isLiked) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
            .clickable(onClick = onPostClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // 收藏时间信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End
            ) {
                Text(
                    text = "收藏于 ${bookmark.bookmarkedTime}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 作者信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.clickable(onClick = onAuthorClick)
            ) {
                // 头像
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(getColorForName(bookmark.authorName)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = bookmark.authorName.first().toString(),
                        style = MaterialTheme.typography.bodyLarge,
                        color = Color.White
                    )
                }
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Column {
                    Text(
                        text = bookmark.authorName,
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = bookmark.formattedTime,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 内容
            Text(
                text = bookmark.content,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            
            if (bookmark.hasImage) {
                Spacer(modifier = Modifier.height(8.dp))
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(150.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(MaterialTheme.colorScheme.secondaryContainer),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "图片内容",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSecondaryContainer
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 操作栏
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                // 点赞
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { isLiked = !isLiked }
                ) {
                    Icon(
                        imageVector = if (isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        tint = if (isLiked) Color.Red else MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = (bookmark.likes + if (isLiked && !bookmark.isLiked) 1 else 0).toString(),
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
                
                // 评论
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        imageVector = Icons.Outlined.InsertComment,
                        contentDescription = "评论",
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = bookmark.comments.toString(),
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
                
                // 移除收藏
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable(onClick = onRemoveBookmark)
                ) {
                    Icon(
                        imageVector = Icons.Default.BookmarkRemove,
                        contentDescription = "移除收藏",
                        modifier = Modifier.size(20.dp)
                    )
                }
                
                // 分享
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        imageVector = Icons.Default.Share,
                        contentDescription = "分享",
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }
    }
}

/**
 * 空收藏状态
 */
@Composable
private fun EmptyBookmarks(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = "暂无收藏内容",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.outline
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = "浏览内容时点击书签图标收藏感兴趣的动态",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.outline,
                textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                modifier = Modifier.padding(horizontal = 32.dp)
            )
        }
    }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 书签/收藏数据类
 */
data class Bookmark(
    val id: String,
    val authorId: String,
    val authorName: String,
    val content: String,
    val timestamp: Long,
    val bookmarkedAt: Long,
    val likes: Int,
    val comments: Int,
    val hasImage: Boolean,
    val isLiked: Boolean
) {
    val formattedTime: String
        get() {
            val now = System.currentTimeMillis()
            val diff = now - timestamp
            
            return when {
                diff < 60 * 1000 -> "刚刚"
                diff < 60 * 60 * 1000 -> "${diff / (60 * 1000)}分钟前"
                diff < 24 * 60 * 60 * 1000 -> "${diff / (60 * 60 * 1000)}小时前"
                else -> {
                    val days = diff / (24 * 60 * 60 * 1000)
                    when {
                        days < 30 -> "${days}天前"
                        else -> "${days / 30}月前"
                    }
                }
            }
        }
    
    val bookmarkedTime: String
        get() {
            val sdf = SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault())
            return sdf.format(Date(bookmarkedAt))
        }
}

/**
 * 生成示例收藏数据
 */
private fun generateSampleBookmarks(count: Int): List<Bookmark> {
    val random = Random
    val currentTime = System.currentTimeMillis()
    val dayInMillis = 24 * 60 * 60 * 1000L
    
    val userNames = listOf("张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十")
    
    val contents = listOf(
        "这款新手机的拍照功能真的太强了，夜景模式表现尤其惊艳，完全不需要再带单反出门了！",
        "今天去爬了黄山，风景如画，真的太美了！登顶后看云海的感觉简直无法形容，推荐大家有机会一定要去。",
        "分享一个我最近发现的小众咖啡馆，环境安静，咖啡品质一流，最适合周末放松或工作。地址在城西银泰附近。",
        "最近在学习Swift编程，感觉语法相比Objective-C更现代化，开发效率确实提高了不少。",
        "昨天看完了《沙丘》第二部，视觉效果和故事叙事都非常震撼，完全展现了科幻的宏大世界观。",
        "自制了一款低脂的希腊酸奶水果沙拉，既健康又美味，做法超简单：酸奶+各种水果+少量蜂蜜，搭配燕麦食用更佳。",
        "今天公司团建去划了皮划艇，虽然一开始有点紧张，但很快就上手了，是个很棒的户外活动选择！",
        "最近在研究人工智能绘画，MidJourney的效果真的让人惊叹，感觉技术发展太快了。",
        "推荐一本近期读的书《原子习惯》，讲述了如何通过微小的行为改变建立长期的好习惯，非常实用。",
        "今天终于完成了马拉松训练计划的最后一次长跑，准备下个月参加城市半程马拉松，有点紧张也有点期待！"
    )
    
    return List(count) { index ->
        val randomUserIndex = random.nextInt(userNames.size)
        val timestamp = currentTime - random.nextLong(1, 60) * dayInMillis / random.nextInt(1, 30)
        val bookmarkedAt = timestamp + random.nextLong(1, 15) * dayInMillis / random.nextInt(1, 10)
        
        Bookmark(
            id = "bookmark-$index",
            authorId = "user-$randomUserIndex",
            authorName = userNames[randomUserIndex],
            content = contents[random.nextInt(contents.size)],
            timestamp = timestamp,
            bookmarkedAt = bookmarkedAt,
            likes = random.nextInt(5, 500),
            comments = random.nextInt(0, 100),
            hasImage = random.nextBoolean(),
            isLiked = random.nextBoolean()
        )
    }
} 